package org.osito.jbehave.loader;

import static org.apache.commons.lang.StringUtils.join;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;

import org.jbehave.core.io.StoryLoader;
import org.odftoolkit.odfdom.doc.OdfTextDocument;
import org.w3c.dom.NodeList;

public class ODFStoryLoader implements StoryLoader {

	@Override
	public String loadStoryAsText(String storyPath) {
		OdfTextDocument document = loadOdfDocument(storyPath);
		List<String> content = getTextContent(document);
		return join(content, newLine());
	}

	private String newLine() {
		return System.getProperty("line.separator");
	}

	private List<String> getTextContent(OdfTextDocument document) {
		List<String> content = new ArrayList<String>();
		XPath xpath = document.getXPath();
		try {
			NodeList nodeList = (NodeList) xpath.evaluate("//text:h|//text:p", document.getContentDom(), XPathConstants.NODESET);
			for (int i = 0; i < nodeList.getLength(); i++) {
				content.add(nodeList.item(i).getTextContent());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return content;
	}

	private OdfTextDocument loadOdfDocument(String storyPath) {
		try {
			return (OdfTextDocument) OdfTextDocument.loadDocument(getClass().getClassLoader().getResourceAsStream(storyPath));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
